// utils/http.js
let BASE_URL = 'http://localhost:9902';
if (process.env.NODE_ENV === 'development') {
	BASE_URL = 'http://localhost:9901';
}

// 请求拦截器：添加全局配置（如Token）
const requestInterceptor = (config) => {
	const token = uni.getStorageSync('token');
	if (token) {
		config.header = {
			...config.header,
			Authorization: `Bearer ${token}`, // 添加Token认证头
		};
	}
	uni.showLoading({
		title: '加载中...',
		mask: true
	}); // 全局加载提示
	return config;
};

// 响应拦截器：统一处理错误码
const responseInterceptor = (response) => {
	uni.hideLoading();
	const {
		statusCode,
		data
	} = response;
	if (statusCode >= 400) {
		handleError(statusCode, data);
		return Promise.reject(response);
	}
	return data;
};

// 错误处理逻辑
const handleError = (statusCode, data) => {
	let message = '请求失败';
	switch (statusCode) {
		case 401:
			message = '未授权，请重新登录';
			uni.removeStorageSync('token');
			uni.reLaunch({
				url: '/pages/login/login'
			}); // 跳转登录页
			break;
		case 403:
			message = '权限不足，请联系管理员';
			break;
		default:
			message = data?.message || '服务器错误';
	}
	uni.showToast({
		title: message,
		icon: 'none'
	});
};

// 封装核心请求方法
const request = (options) => {
	const config = requestInterceptor(options);
	return new Promise((resolve, reject) => {
		uni.request({
			url: BASE_URL + config.url,
			method: config.method,
			data: config.data,
			header: config.header,
			success: (res) => {
				const processed = responseInterceptor(res);
				resolve(processed);
			},
			fail: (err) => {
				uni.hideLoading();
				uni.showToast({
					title: '网络异常',
					icon: 'none'
				});
				reject(err);
			},
		});
	});
};

// 提供直接调用的GET/POST方法
export const http = {
	get: (url, params = {}) => request({
		url,
		method: 'GET',
		data: params
	}),
	post: (url, data) => request({
		url,
		method: 'POST',
		data
	}),
	// 可扩展其他方法（如PUT、DELETE）
};